package event

import (
	"context"
	"errors"
	"gorm.io/gorm"
)

var db *gorm.DB

const DBList = "comList"

type CommandHandler func(db *gorm.DB) error

var (
	ErrNoDB       = errors.New("db not set")
	ErrDBListType = errors.New("ErrDBListType")
)

func SetGorm(setDB *gorm.DB) {
	db = setDB
}

func WriteWithContext(ctx context.Context) error {

	value := ctx.Value(DBList)
	if value == nil {
		return nil
	}
	dbList, ok := value.(*[]CommandHandler)
	if !ok {
		return ErrDBListType
	}

	if dbList == nil || len(*dbList) == 0 {
		return nil
	}

	err := db.Transaction(func(tx *gorm.DB) error {
		for _, dbCom := range *dbList {
			err := dbCom(tx)
			if err != nil {
				return err
			}
		}

		return nil
	})
	if err != nil {
		return err
	}

	return nil
}

func Command(ctx context.Context, handler CommandHandler) {
	if mode == DEBUG {
		db.Transaction(func(tx *gorm.DB) error {
			return handler(tx)
		})
		return
	}
	value := ctx.Value(DBList)
	if handler == nil {
		return
	}
	list, ok := value.(*[]CommandHandler)
	if !ok {
		return
	}
	*list = append(*list, handler)
}
